<template>
  <view class="page-container">
    <!-- 导航栏 -->
    <u-navbar title="修改密码" back-icon="arrow-left" />
    
    <!-- 内容区域 -->
    <scroll-view scroll-y="true" class="content-scroll">
      <view class="content-area">
        <u-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
          <view class="form-section">
            <view class="section-title">修改密码</view>
            
            <u-form-item label="当前密码" prop="oldPassword">
              <u-input 
                v-model="passwordForm.oldPassword" 
                placeholder="请输入当前密码"
                type="password"
                :password="true"
              />
            </u-form-item>
            
            <u-form-item label="新密码" prop="newPassword">
              <u-input 
                v-model="passwordForm.newPassword" 
                placeholder="请输入新密码"
                type="password"
                :password="true"
              />
            </u-form-item>
            
            <u-form-item label="确认新密码" prop="confirmPassword">
              <u-input 
                v-model="passwordForm.confirmPassword" 
                placeholder="请再次输入新密码"
                type="password"
                :password="true"
              />
            </u-form-item>
          </view>
          
          <!-- 密码强度提示 -->
          <view class="password-strength" v-if="passwordForm.newPassword">
            <view class="strength-title">密码强度：</view>
            <view class="strength-bar">
              <view 
                class="strength-progress" 
                :class="strengthClass"
                :style="{ width: strengthWidth }"
              ></view>
            </view>
            <view class="strength-text" :class="strengthClass">{{ strengthText }}</view>
          </view>
          
          <!-- 密码要求提示 -->
          <view class="password-requirements">
            <view class="requirements-title">密码要求：</view>
            <view class="requirement-item" :class="{ met: hasLength }">
              <u-icon :name="hasLength ? 'checkmark' : 'close'" :color="hasLength ? '#52c41a' : '#ff4d4f'" size="14" />
              <text>长度至少6位</text>
            </view>
          </view>
        </u-form>
        
        <!-- 权限提示组件 -->
        <permission-tip ref="permissionTip" />
      </view>
    </scroll-view>
    
    <!-- 固定按钮区域 -->
    <view class="form-actions">
      <u-button 
        type="primary" 
        @click="changePassword"
        :loading="changing"
        :disabled="changing || !isPasswordValid"
      >
        确认修改
      </u-button>
      
      <u-button 
        type="default" 
        @click="resetForm"
        :disabled="changing"
      >
        重置
      </u-button>
    </view>
  </view>
</template>

<script>
/**
 * 密码修改页面
 * @author Wu.Liang
 * @date 2025-01-27
 */

import { ref, reactive, computed } from 'vue'
import { useAuthStore } from '@/store'
import PermissionTip from '@/components/PermissionTip.vue'

export default {
  name: 'ChangePassword',
  components: {
    PermissionTip
  },
  setup() {
    const authStore = useAuthStore()
    
    // 表单引用
    const passwordFormRef = ref(null)
    
    // 响应式数据
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const changing = ref(false)
    
    // 表单验证规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 计算属性 - 简化密码强度检查
    const hasLength = computed(() => passwordForm.newPassword.length >= 6)
    
    const passwordStrength = computed(() => {
      return hasLength.value ? 1 : 0
    })
    
    const strengthClass = computed(() => {
      return hasLength.value ? 'strong' : 'weak'
    })
    
    const strengthWidth = computed(() => {
      return hasLength.value ? '100%' : '0%'
    })
    
    const strengthText = computed(() => {
      return hasLength.value ? '密码强度：强' : '密码强度：弱'
    })
    
    const isPasswordValid = computed(() => {
      return hasLength.value
    })
    
    // 方法
    const changePassword = async () => {
      try {
        // 表单验证
        const valid = await passwordFormRef.value.validate()
        if (!valid) {
          return
        }
        
        // 前端校验两次新密码输入是否一致
        if (passwordForm.newPassword !== passwordForm.confirmPassword) {
          uni.showToast({
            title: '两次输入的新密码不一致',
            icon: 'none'
          })
          return
        }
        
        // 检查密码强度
        if (!isPasswordValid.value) {
          uni.showToast({
            title: '请满足密码要求',
            icon: 'none'
          })
          return
        }
        
        changing.value = true
        
        // 获取当前登录用户ID
        const userInfo = uni.getStorageSync('userInfo')
        const currentUserId = userInfo?.id
        if (!currentUserId) {
          uni.showToast({
            title: '获取用户信息失败，请重新登录',
            icon: 'none'
          })
          return
        }
        
        // 调用API修改密码，传递当前密码、新密码、当前登录用户ID
        const result = await authStore.changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
          userId: currentUserId
        })
        
        if (result) {
          uni.showToast({
            title: '密码修改成功',
            icon: 'success'
          })
          
          // 清空表单
          resetForm()
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        uni.showToast({
          title: error.message || '修改失败',
          icon: 'none'
        })
      } finally {
        changing.value = false
      }
    }
    
    const resetForm = () => {
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      passwordFormRef.value.resetFields()
    }
    
    return {
      passwordForm,
      passwordRules,
      changing,
      passwordFormRef,
      hasLength,
      passwordStrength,
      strengthClass,
      strengthWidth,
      strengthText,
      isPasswordValid,
      changePassword,
      resetForm
    }
  }
}
</script>

<style scoped>
/* 页面容器 - 必须完全顶满手机宽度 */
.page-container {
  min-height: 100vh;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 内容区域 - 确保无左右空白 */
.content-scroll {
  flex: 1;
  min-height: 0;
}

.content-area {
  padding: 16px;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.password-strength {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.strength-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.strength-bar {
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 8px;
}

.strength-progress {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-progress.weak {
  background-color: #ff4d4f;
}

.strength-progress.medium {
  background-color: #faad14;
}

.strength-progress.strong {
  background-color: #52c41a;
}

.strength-progress.very-strong {
  background-color: #1890ff;
}

.strength-text {
  font-size: 12px;
  text-align: center;
}

.strength-text.weak {
  color: #ff4d4f;
}

.strength-text.medium {
  color: #faad14;
}

.strength-text.strong {
  color: #52c41a;
}

.strength-text.very-strong {
  color: #1890ff;
}

.password-requirements {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.requirements-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.requirement-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #999;
}

.requirement-item.met {
  color: #52c41a;
}

/* 固定按钮区域 */
.form-actions {
  flex-shrink: 0;
  display: flex;
  gap: 12px;
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

.form-actions .u-button {
  flex: 1;
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .content-area {
    padding: 12px;
  }
  
  .form-section {
    padding: 12px;
    margin-bottom: 12px;
  }
  
  .form-actions {
    padding: 12px;
  }
}

@media screen and (min-width: 414px) {
  .page-container {
    max-width: 400px;
    margin: 0 auto;
  }
}

@media screen and (orientation: landscape) {
  .page-container {
    height: 100vh;
  }
  
  .content-area {
    padding: 20px;
  }
}
</style> 